const express = require('express');
const path = require('path');
const compression = require('compression');
const helmet = require('helmet');
const fs = require('fs');

const app = express();
const PORT = process.env.PORT || 3000;
const NODE_ENV = process.env.NODE_ENV || 'production';

console.log(`🌍 环境: ${NODE_ENV}`);
console.log(`📁 工作目录: ${__dirname}`);
console.log(`📁 静态文件目录: ${path.join(__dirname, 'public')}`);

// 生产环境安全配置
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'", "https://cdn.tailwindcss.com", "https://cdnjs.cloudflare.com"],
      scriptSrc: ["'self'", "'unsafe-inline'", "https://cdn.tailwindcss.com"],
      imgSrc: ["'self'", "data:", "https:"],
      fontSrc: ["'self'", "https://cdnjs.cloudflare.com"],
      mediaSrc: ["'self'", "data:"]
    }
  },
  crossOriginEmbedderPolicy: false
}));

// 启用gzip压缩
app.use(compression());

// 设置视图引擎
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// 详细的静态文件服务配置
const publicDir = path.join(__dirname, 'public');

// 检查public目录是否存在
if (!fs.existsSync(publicDir)) {
  console.error(`❌ 错误: public目录不存在: ${publicDir}`);
  process.exit(1);
}

console.log(`✅ public目录存在: ${publicDir}`);

// 配置静态文件服务
app.use('/css', express.static(path.join(publicDir, 'css'), {
  setHeaders: (res, path) => {
    res.set('Cache-Control', 'public, max-age=31536000');
    console.log(`📁 提供CSS文件: ${path}`);
  }
}));

app.use('/images', express.static(path.join(publicDir, 'images'), {
  setHeaders: (res, path) => {
    res.set('Cache-Control', 'public, max-age=31536000');
    console.log(`📁 提供图片文件: ${path}`);
  }
}));

app.use('/js', express.static(path.join(publicDir, 'js'), {
  setHeaders: (res, path) => {
    res.set('Cache-Control', 'public, max-age=31536000');
    console.log(`📁 提供JS文件: ${path}`);
  }
}));

app.use('/video', express.static(path.join(publicDir, 'video'), {
  setHeaders: (res, path) => {
    res.set('Cache-Control', 'public, max-age=31536000');
    console.log(`📁 提供视频文件: ${path}`);
  }
}));

// 通用静态文件服务作为备用
app.use(express.static(publicDir, {
  setHeaders: (res, path) => {
    console.log(`📁 提供静态文件: ${path}`);
  }
}));

// 请求日志中间件
app.use((req, res, next) => {
  const timestamp = new Date().toISOString();
  console.log(`[${timestamp}] ${req.method} ${req.url}`);
  console.log(`   IP: ${req.ip}`);
  console.log(`   User-Agent: ${req.get('User-Agent')}`);
  
  // 记录静态文件请求
  if (req.url.match(/\.(css|js|png|jpg|jpeg|gif|mp4|webm)$/)) {
    console.log(`   📁 静态文件请求: ${req.url}`);
  }
  
  next();
});

// 路由
app.get('/', (req, res) => {
  console.log('🏠 渲染首页');
  res.render('index', {
    title: '潮汐漂流瓶 - 波纹写满故事，潮汐见证相逢',
    description: '潮汐漂流瓶是一款温暖的社交应用，让你在数字海洋中投掷文字瓶子，与陌生人邂逅美好故事。',
    keywords: '漂流瓶,社交,聊天,交友,文字,故事,相遇'
  });
});

app.get('/privacy', (req, res) => {
  res.render('privacy', {
    title: '隐私政策 - 潮汐漂流瓶',
    description: '潮汐漂流瓶隐私政策说明'
  });
});

app.get('/terms', (req, res) => {
  res.render('terms', {
    title: '用户协议 - 潮汐漂流瓶',
    description: '潮汐漂流瓶用户协议说明'
  });
});

// 静态文件状态检查
app.get('/status', (req, res) => {
  const status = {
    environment: NODE_ENV,
    timestamp: new Date().toISOString(),
    server: 'running',
    publicDir: publicDir,
    staticFiles: {
      css: {
        exists: fs.existsSync(path.join(publicDir, 'css')),
        files: fs.existsSync(path.join(publicDir, 'css')) ? fs.readdirSync(path.join(publicDir, 'css')) : []
      },
      images: {
        exists: fs.existsSync(path.join(publicDir, 'images')),
        files: fs.existsSync(path.join(publicDir, 'images')) ? fs.readdirSync(path.join(publicDir, 'images')) : []
      },
      js: {
        exists: fs.existsSync(path.join(publicDir, 'js')),
        files: fs.existsSync(path.join(publicDir, 'js')) ? fs.readdirSync(path.join(publicDir, 'js')) : []
      },
      video: {
        exists: fs.existsSync(path.join(publicDir, 'video')),
        files: fs.existsSync(path.join(publicDir, 'video')) ? fs.readdirSync(path.join(publicDir, 'video')) : []
      }
    }
  };
  
  res.json(status);
});

// 404处理
app.use((req, res) => {
  console.log(`❌ 404 Not Found: ${req.url}`);
  res.status(404).json({
    error: '页面未找到',
    url: req.url,
    timestamp: new Date().toISOString(),
    suggestion: '请检查URL是否正确，或访问 /status 查看服务器状态'
  });
});

// 错误处理
app.use((err, req, res, next) => {
  console.error('💥 服务器错误:', err.stack);
  res.status(500).json({
    error: '服务器内部错误',
    message: err.message,
    timestamp: new Date().toISOString()
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 潮汐漂流瓶官网启动成功!`);
  console.log(`🌐 访问地址: http://localhost:${PORT}`);
  console.log(`📊 状态检查: http://localhost:${PORT}/status`);
  console.log(`📁 静态文件目录: ${publicDir}`);
  console.log(`⏰ 启动时间: ${new Date().toISOString()}`);
});

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('🛑 收到SIGTERM信号，正在关闭服务器...');
  process.exit(0);
});

process.on('SIGINT', () => {
  console.log('🛑 收到SIGINT信号，正在关闭服务器...');
  process.exit(0);
});
